from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.db import connection
import requests
import json
import time 
import os
from django.http import HttpResponseRedirect
from django.urls import reverse
from yxb import common_tools

class File_object:
    def __init__(self, file_name, title, content, score):
        self.file_name = file_name
        self.title = title
        self.content = content
        self.score = score


def index(request):
    api_request = requests.get("http://www.baidu.com")
    resp = {
        'title':'    title 标题  >>>  ',
        "key": api_request.content
    }
    obj_0 = File_object("file_00", "Docker 安装 Java JDK 8" , "Docker 的旧版本被称为 docker，docker.io 或 docker-engine 。如果已安装，请卸载它们：" , 56)
    obj_1 = File_object("file_11", "JavaScript 教程" , "JavaScript 是 Web 的编程语言。所有现代的 HTML 页面都可以使用 JavaScript。" , 12)
    print(obj_0.title)
    return render(request,'Add/index.html', {'data': json.dumps(obj=obj_0.__dict__,ensure_ascii=False)})

@csrf_exempt
def ajax_new(request):
    if request.method == 'POST':
        post_data = json.loads(request.body.decode('utf-8'))
        string_data = post_data.get('string_data', '')
        string_data = common_tools.clean_string(string_data)

        select_value = post_data.get('select_value', '')
        print(string_data)
        print(select_value)
        current_path = os.path.abspath(__file__)
        parent_folder = os.path.dirname(os.path.dirname(current_path))
        print("父文件夹:  ")
        print(parent_folder + "\TXT")
        time_now = time.strftime("%Y_%m_%d_%H%M%S", time.localtime())
        file_full_path = parent_folder + "\TXT" + "\\" + str(time_now) + ".txt"
        print(file_full_path)
        common_tools.write_to_txt_file(string_data, select_value, file_full_path)
        return HttpResponse("success", content_type="application/json")
    else:
        return HttpResponse("false", content_type="application/json")


@csrf_exempt
def ajax_post_test(request):
    if request.method == 'POST':
        print("ajax test =============================")
        return HttpResponse("哈哈哈哈哈哈哈哈哈", content_type="application/json")
    else:
        return HttpResponse("哈哈哈哈哈哈哈哈哈", content_type="application/json")


def get_aaa(request, aaa):
    # 使用aaa参数的值进行处理
    print(aaa)
    print(aaa)
    return HttpResponse(aaa, content_type="application/json")